Adding Custom Nodes

The previous steps have shown how to customise the appearance and user interaction of the property grid, but what if you need to customise the data model? For example, suppose your application allows users to record comments against each object they edit, but that these comments are stored separately as metadata rather than as part of the object itself.

Adding a Node to the Grid

To add a Comments field to the grid, call the AddNode method:

CopyAdding a custom node
1_commentsNode = PropertyGrid.AddNode("Comments", String.Empty);

You can retrieve the current value of the node, as edited by the user, using the Value property:

CopyRetrieving the edited value
1string comments = _commentsNode.Value as string;

It is your code’s responsibility to retrieve the edited value of the node and to store or otherwise act on it. The property grid provides only editing services: it does not track or persist nodes or maintain any association between the added nodes and the SelectedObject.

If you need a completely custom data model, you can leave SelectedObject at null, and manage all the nodes yourself using AddNode and RemoveNode.
 

Customizing the Editing Experience for Custom Nodes

Custom nodes use the same editors as normal properties. A property editor matches the custom node if the DeclaringType of the property editor is null, and the caption of the custom node matches the PropertyName of the property editor. A type editor matches the custom node if the value of the node is of the appropriate type.

However, property editors are usually set up in XAML at design time, whereas you may not know the name of the custom node until run time. Although you can add a PropertyEditor to the editors collection from code when you add the node, there is the risk that this will affect other nodes that happen to share a name. Therefore the AddNode method allows you to associate a custom editor specifically with the custom node by passing in a DataTemplate or the resource key of a DataTemplate.

In this example, a custom boolean node is assigned the built-in check box editor:

CopyAdding a custom node with a custom editor
1PropertyGrid.AddNode("Approved", false, PropertyGrid.CheckBoxEditorKey);

Editing Properties from Multiple Objects

The previous examples create nodes over raw values, and it’s up to your application to handle retrieval and storage of those values. You can also display and edit properties from objects other than the SelectedObject. Changes to these properties are reflected in the source object; your application doesn’t need to do anything special to retrieve the values.

To add selected properties from an object to the grid, call the AddPropertyNode method:

CopyAdding a property of another object
1PropertyGrid.AddPropertyNode(Pet.Dinah, "Name", "Pet's Name");

See 06_AddingCustomNodes.xaml in the PropertyGridCustomization project.

Next step: Improving Error Handling